<script setup lang="ts">
import { onBeforeMount, onUnmounted, provide, ref, nextTick } from 'vue'
import { useRouter } from 'vue-router'
import type { RouteRecordRaw } from 'vue-router'
import { useCurrentUserStore } from '@/modules/security/stores/currentUserStores'
import { useRouterStore } from '@/modules/security/stores/routerStores'
import { webSocketStore } from '@/modules/socket/stores/webSocket'
import { securityApi } from '@/modules/security/api'
import type { CurrentUser } from '@/modules/security/entity'
import AdminHeader from './components/AdminHeader.vue'
import AdminMain from './components/AdminMain.vue'

// 初始化路由和状态管理
const router = useRouter()
const userStore = useCurrentUserStore()
const routerStore = useRouterStore()
const wsSession = webSocketStore()

// 响应式数据
const routes = ref<RouteRecordRaw[]>([])
const level1RouterPath = ref<string>('/admin')  // 默认为权限管理路径
const info = ref<CurrentUser | null>(null)

/**
 * 初始化用户信息和路由
 */
const initUserAndRoutes = async () => {
  if (!userStore.currentUser?.user?.username) {
    try {
      const res = await securityApi.userInfo()
      userStore.setUser(res.data)
    } catch {  // 不使用参数
      userStore.clearUser()
      await router.push('/login')
      return false
    }
  }
  return true
}


/**
 * 处理菜单选择
 */
const handleSelect = (key: string) => {
  // 如果是首页路径，直接设置
  if (key === '/admin') {
    level1RouterPath.value = '/admin'
    return
  }

  const selectedRoute = routes.value.find(r => {
    const fullPath = r.path.startsWith('/') ? r.path : `/admin/${r.path}`
    return fullPath === key || key === r.path
  })

  if (selectedRoute) {
    // 更新一级路由路径
    level1RouterPath.value = selectedRoute.path.startsWith('/') ?
      selectedRoute.path : `/admin/${selectedRoute.path}`
  }
}

// 组件挂载前的初始化
onBeforeMount(async () => {
  if (!userStore.isLoggedIn()) {
    await router.push('/login')
    return
  }

  if (await initUserAndRoutes()) {
    info.value = userStore.currentUser
    // 获取顶部导航路由
    routes.value = routerStore.getCurrentUserRouterList(info.value.menus,'admin')
    
    // 根据当前路径初始化菜单状态
    const currentPath = router.currentRoute.value.path
    if (currentPath === '/admin') {
      level1RouterPath.value = '/admin'
    } else {
      const segments = currentPath.split('/')
      if (segments.length >= 3) {
        const parentPath = `/${segments[1]}/${segments[2]}`
        await nextTick(() => handleSelect(parentPath))
      }
    }

    if (!wsSession.session?.wsConnected) {
      wsSession.connectWebSocket()
    }
  }
})

// 组件卸载时清理
onUnmounted(() => {
  wsSession.unSubMessage('/admin/home')
})

// 提供给子组件使用的方法和数据
provide('handleSelect', handleSelect)
provide('level1RouterPath', level1RouterPath)
</script>

<template>
  <div class="admin-layout">
    <el-container>
      <el-header>
        <AdminHeader
          :routes="routes"
          @handleSelect="handleSelect">
        </AdminHeader>
      </el-header>
      <el-main>
        <AdminMain 
          :level1-router-path="level1RouterPath"
        ></AdminMain>
      </el-main>
    </el-container>
  </div>
</template>

<style scoped lang="scss">

</style>
